/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: Pegasus  Date: 2018-12-16 Time: 17:25
 *
 * 新建报修工单 => 选择
 */

import React, {Component} from 'react';
import {
    SafeAreaView,
    View,
    TouchableOpacity,
    Text,
    ScrollView,BackHandler,Platform,TextInput
} from 'react-native';
import {connect} from 'react-redux';
import {styles} from "./RepairWorkOrderChoosePlaceOrObjectScreen.Style";
import {COLOR_THEME, FONT_COLOR_SUB_TITLE} from "../../../../constant/PHColors";
import AntDesign from "react-native-vector-icons/AntDesign";
import Entypo from "react-native-vector-icons/Entypo";
import {SCREEN_WIDTH} from "../../../../constant/PHScreen"
import HS_TouchableHighlight from "../../../../hsstyle/HS_TouchableHighlight"

class RepairWorkOrderChoosePlaceOrObjectScreen extends Component {

    static navigationOptions = ({ navigation }) =>({
        title: "选择报修"+navigation.state.params.title,
    });

    //构造
    constructor(props) {
        super(props);

        this.state = {
            modalVisible:false,
            classVisible:true,
            searchVisible:false,
            areaLevel:1, //菜单级数
            areaSn:'',//菜单Sn码
            menuArr:[{"name":this.props.navigation.getParam("title"),"sn":"","level":0}],//菜单索引（第一行）
            searchText:'',//查询内容
        };
    };

    componentWillMount() {
        if (Platform.OS === 'android'||Platform.OS==='ios') {
            BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
        }
    };

    componentWillUnmount() {
        if (Platform.OS === 'android'||Platform.OS==='ios') {
            BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
        }
    };

    render() {
        // console.log(this.props.onCache)
        return (
            <SafeAreaView style={{flex: 1}}>
                <View style={styles.container}>
                    <View style={styles.searchBox}>
                        <AntDesign name={'search1'} size={17} style={{color: FONT_COLOR_SUB_TITLE}}/>
                        <TextInput style={styles.inputText}
                                   keyboardType='web-search'
                                   placeholder='搜索'
                                   onChangeText={text => {
                                       this._search(text)
                                   }}
                                   defaultValue = {this.state.searchText}
                        />
                        {
                            this.state.searchText!=="" && (
                                <View style={styles.searchBoxRight}>
                                    <AntDesign name={'closecircle'} size={18} style={{color: '#d7d7d7'}} onPress={()=>{
                                        this._search('')
                                    }}/>
                                </View>
                            )
                        }
                    </View>
                </View>
                <View  style={{height: 40, flexDirection: 'row',backgroundColor:'#e8e8e8',width:SCREEN_WIDTH,borderBottomColor:'#e8e8e8',borderBottomWidth: 1,}}>
                    {
                        this.state.menuArr.map((item, index) => {
                            return this._menuRender(item, index)
                        })
                    }
                </View>
                {
                    this.state.modalVisible && (
                        <ScrollView style={{flex: 1}}>
                            {
                                this.props.onCache[this.props.navigation.getParam("type")].map((item, index) => {
                                    let areaSnLength = this.state.areaSn.length;
                                    if(parseInt(item.level)===this.state.areaLevel&&this.state.areaSn===item.sn.substring(0,areaSnLength)){
                                        return this._areaModalRender(item, index)
                                    }
                                })
                            }
                        </ScrollView>
                    )
                }
                {
                    this.state.classVisible && (
                        <ScrollView style={{flex: 1}}>
                            {
                                this.props.onCache[this.props.navigation.getParam("type")].map((item, index) => {
                                    return this._areaRender(item, index)
                                })
                            }
                        </ScrollView>
                    )
                }
                {
                    this.state.searchVisible && (
                        <ScrollView style={{flex: 1}}>
                            {
                                this.props.onCache[this.props.navigation.getParam("type")].map((item, index) => {
                                    return this._searchRender(item, index)
                                })
                            }
                        </ScrollView>
                    )
                }
            </SafeAreaView>
        )
    };

    onBackAndroid = () =>{
        this.state.areaLevel--;
        if(this.state.areaLevel===0){
            // getStore().dispatch(NavigationActions.back());
            this.props.navigation.state.params.goBack();
            // return false;
        }else if(this.state.areaLevel===1){
            this.state.areaSn = this.state.areaSn.split('.').pop();
            this.state.menuArr.pop();
            this.setState({
                modalVisible: false,
                classVisible:true,
                searchVisible:false,
            });
            return true;
        }else if(this.state.areaLevel>1){
            this.state.menuArr.pop();
            let arr = this.state.areaSn.split('.');
            if(arr.length>2){
                arr.pop();
                this.state.areaSn = arr.join('.');
            }else if(arr.length===2){
                arr.pop();
                this.state.areaSn = arr[0];
            }
            this.setState({
                modalVisible: true,
                classVisible:false,
                searchVisible:false,
            });
            return true;
        }
        return true;
    };

    _search(text){
        if(text===""){
            this.state.areaLevel=1;
            this.state.areaSn="";
            this.state.menuArr=[{"name":this.props.navigation.getParam("title"),"sn":"","level":0}];
            this.setState({modalVisible: false,classVisible:true,searchVisible:false,searchText:''});
        }else{
            this.setState({modalVisible: false,classVisible:false,searchVisible:true,searchText:text});
        }
    }

    _searchRender(item, index){
        if(!item['shortcut']){
            item.shortcut=''
        }
        if(!item['name']){
            item.name=''
        }
        if(Number(item.name.indexOf(this.state.searchText))>=0||Number((item.shortcut.toUpperCase()).indexOf((this.state.searchText.toUpperCase())))>=0){
            return(
                <HS_TouchableHighlight key={index} activeOpacity={0.8}  onPress={() => {
                    this.state.areaLevel=1;//菜单级数
                    this.state.areaSn = '';//菜单Sn码
                    let returnJson = {};
                    returnJson[this.props.navigation.getParam("type")] = item.fullname;
                    returnJson[this.props.navigation.getParam("type")+"_sn"] = item.sn;
                    // this.props.navigation.navigate(this.props.navigation.getParam("returnPage"),returnJson)
                    this.props.navigation.state.params.goBack(returnJson);
                }}>
                    <View style={styles.boxBody}>
                        <View style={styles.leftBox}>
                            <Text style={styles.centerText}>
                                {item.fullname}
                            </Text>
                        </View>
                    </View>
                </HS_TouchableHighlight>
            )
        }
    }

    //菜单索引
    _menuRender(item, index){
        console.log(JSON.stringify(this.state.menuArr))
        if(index===0){
            return(
                <TouchableOpacity activeOpacity={1} key={index}  style={styles.clickButtonStyle} onPress={()=>{
                    this.state.areaLevel=1;
                    this.state.areaSn=item.sn;
                    this.state.menuArr.splice(index+1,this.state.menuArr.length-parseInt(index));
                    this.setState({modalVisible: false,classVisible:true,searchVisible:false,});
                }}>
                    <Text style={{fontSize:20}}>{item.name}</Text>
                </TouchableOpacity>
            )
        }else{
            return(
                <View key={index} style={{flexDirection: 'row',}}>
                    <Text style={{flexDirection:'row',marginTop: 12}}>
                        <AntDesign name={'doubleright'} size={15} style={{color: FONT_COLOR_SUB_TITLE}}/>
                    </Text>
                    <TouchableOpacity activeOpacity={1} style={styles.clickButtonStyle} onPress={()=>{
                        this.state.areaLevel=parseInt(item.level)+1;
                        this.state.areaSn=item.sn;
                        this.state.menuArr.splice(index+1,this.state.menuArr.length-parseInt(index));
                        this.setState({modalVisible: true,classVisible:false,searchVisible:false,});
                    }}>
                        <Text style={{fontSize:20}}>{item.name}</Text>
                    </TouchableOpacity>
                </View>

            )
        }

    };

    //主列表
    _areaRender(item, index){
        console.log(JSON.stringify(item))
        if(item.level==='1' || item.level===1){
            return(
                <HS_TouchableHighlight key={index} onPress={() => {
                    if(item.node==='D'){//有下一级
                        this.state.menuArr.push({"name":item.name,"sn":item.sn,"level":item.level});
                        this.setState({modalVisible: true,classVisible:false,searchVisible:false,});
                        this.state.areaLevel++;
                        this.state.areaSn = item.sn;
                    }else{//没下一级
                        this.state.areaLevel=1;//菜单级数
                        this.state.areaSn = '';//菜单Sn码
                        let returnJson = {};
                        returnJson[this.props.navigation.getParam("type")] = item.fullname;
                        returnJson[this.props.navigation.getParam("type")+"_sn"] = item.sn;
                        // this.props.navigation.navigate(this.props.navigation.getParam("returnPage"),returnJson)
                        this.props.navigation.state.params.goBack(returnJson);
                    }
                }}>
                    <View style={styles.boxBody}>
                        <View style={styles.leftBox}>
                            <Text style={styles.centerText}>
                                {item.name}
                            </Text>
                        </View>
                        {this._level1(item.node,item.sn)}
                    </View>

                </HS_TouchableHighlight>
            )
        }
    };

    //模态循环列表
    _areaModalRender(item, index){
        return(
            <View key={index} style={{width:SCREEN_WIDTH, flexDirection: 'row',flexWrap: 'wrap',height: 55}} >
                <HS_TouchableHighlight  onPress={() => {
                    if(item.node==='D'){//有下一级
                        this.state.menuArr.push({"name":item.name,"sn":item.sn,"level":item.level});
                        this.setState({
                            modalVisible: true,
                            classVisible: false,
                            searchVisible:false,
                        });
                        this.state.areaLevel++;
                        this.state.areaSn = item.sn;
                    }else{//没下一级
                        this.state.areaLevel=1;//菜单级数
                        this.state.areaSn = '';//菜单Sn码
                        let returnJson = {};
                        returnJson[this.props.navigation.getParam("type")] = item.fullname;
                        returnJson[this.props.navigation.getParam("type")+"_sn"] = item.sn;
                        // this.props.navigation.navigate(this.props.navigation.getParam("returnPage"),returnJson)
                        this.props.navigation.state.params.goBack(returnJson);
                    }
                }}>
                    <View style={styles.boxBody} >
                        <View style={styles.leftBox}>
                            <Text style={styles.centerText}>
                                {item.name}
                            </Text>
                        </View>
                        {this._level1(item.node,item.sn)}
                    </View>
                </HS_TouchableHighlight>
            </View>
        )

    };

    _level1 = (node,sn) => {
        if(node==='D'){
            return(
                <View style={styles.rightBox}>
                    <AntDesign name={'right'} size={17} style={{color: FONT_COLOR_SUB_TITLE}}/>
                </View>
            )
        }else if(this.props.navigation.getParam("sn")===sn){
            return(
                <View style={styles.rightBox}>
                    <Entypo name={'check'} size={22} style={{color: COLOR_THEME, fontWeight: 'bold'}}/>
                </View>
            )
        }
    };
}

const props = state => {
    return {
        onCache: state.onCache,
    }
};

export default RepairWorkOrderChoosePlaceOrObjectScreen = connect(props)(RepairWorkOrderChoosePlaceOrObjectScreen);
